<template>
  <div style="margin:5px 0 5px 0">
    当前答题剩余有效时间
    <span class="getRed">{{times}}</span>
    秒
    <el-button type="primary" @click="getendTime" :disabled="canClick">开始答题</el-button>
  </div>
  <div>
    <el-form ref="modelForm" :model="modelForm" label-position="right" label-width="100px">
      <div v-for="(item, index) in modelForm.topic" :key="index">
        <el-collapse>
          <el-collapse-item :key="index">
            <template v-slot:title="title">
              第{{ index+1 }}题:{{ item.questionName }}
            </template>
            <!-- 答案 -->
            <el-radio-group
                v-model="item.answer"
                v-if="item.type == 1"
                @change="getTo(item,index)"
                :disabled="canAnswer"

            >
                <el-radio
                    v-for="(opt, idx) in item.answers"
                    :key="idx"
                    :label="opt.choiceText"
                    :prop="`topic.${index}.answers.${idx}.choiceText`"
                >{{opt.choiceText}}</el-radio>
            </el-radio-group>

            <el-checkbox-group
                v-model="item.answer2"
                v-if="item.type == 2"
                :disabled="canAnswer"
            >
              <el-checkbox
                  v-for="(opt, idx) in item.answers"
                  :key="idx"
                  :label="opt.choiceText"
                  :prop="`topic.${index}.answers.${idx}.choiceText`"
              >{{opt.choiceText}}</el-checkbox>
            </el-checkbox-group>
            <el-form-item v-if="item.type == 3">
              <el-input v-model="item.answer" :disabled="canAnswer" @input="change"></el-input>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div align="center">
        <el-form-item>
          <el-button  id="155" style="margin-top: 10px" @click="submit" type="primary">提交</el-button>
        </el-form-item>
      </div>

    </el-form>
    <!--    <el-button @click="loadData()">测试</el-button>-->
  </div>
  <el-dialog v-model="dialogVisible" title="Tips" width="30%" draggable show-close="false">
    <span>您的答题时间已到，作答记录已自动提交！</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onsure">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import timeChanage from "@/components/TimeChanage";
import router from "@/router";
import { useRoute } from "vue-router";
import element, {ElMessage,ElMessageBox} from 'element-plus'
import TimeChange from "@/components/TimeChanage";
export default {
  name: "AnswerView",
  components: {TimeChange},
  data() {
    return {
      aid:'',
      canClick:false,
      dialogVisible:false,
      canAnswer:true,
      isSub:false,
      qid: this.$cookies.get('qid'),
      times: 60,
      modelForm: {
        topic: []
      },
      modelForm2: {
        topic: []
      },
      toQues:[]
    }
  },
  methods: {
    onsure(){
      this.dialogVisible = false
      router.push('/answered')
    },
    change(){
      console.log(1)
    },
    getendTime(){
      this.canClick=true
      let endMsRes = (new Date()).getTime() + this.times * 1000;
      console.log(endMsRes)
      //Setitem 为封装 localStoryge 方法
      localStorage.setItem('myEndTime'+this.aid, JSON.stringify(endMsRes));
      localStorage.setItem('canClick'+this.aid, JSON.stringify(this.canClick));
		  this.getTime(endMsRes)
    },
    getTime(endMsRes) {
      this.canAnswer=false
      if(!this.isSub){
        this.times=Math.ceil((endMsRes - (new Date()).getTime()) / 1000)
        let time = setTimeout(() => {
          this.times--
          if (this.times< 1) {
            this.canClick = false
            this.dialogVisible=true
            console.log(this.modelForm.topic)
            this.postRes()
            this.canAnswer=true

            clearTimeout(time)
          } else {
            this.getTime(endMsRes)
          }
        }, 1000)
      }

    },
    postRes() {
      let list=[]
      let self = this
      console.log(this.modelForm)
      this.modelForm.topic.forEach(function (item){
        if (item.type=='1' || item.type=='3'){
          list.push({aid:item.aid,questionId:item.quesId,answerContent:item.answer})
        }
        else
        {
          for (let i = 0; i < item.answer2.length; i++) {
            list.push({aid:item.aid,questionId:item.quesId,answerContent:item.answer2[i]})
          }
          if (item.answer2.length == 0){
            list.push({aid:item.aid,questionId:item.quesId,answerContent:''})
          }
        }

      })
      console.log(list)
      this.$axios.post('http://localhost:8090/question-history/insertBatchHistory',{
        list:list,
        qid:self.qid
      }).then(res=>res.data).then(res=>{
        if(res.code == '200'){
          localStorage.removeItem('form'+self.aid)
          localStorage.removeItem('toQues'+self.aid)
          localStorage.removeItem('myEndTime'+self.aid)
          localStorage.removeItem('canClick'+self.aid)

          ElMessage({
            type: 'success',
            message: '作答记录已提交',
          })
          router.push('/answered')
        }
      })

    },
    submit(e) {
      localStorage.removeItem('form'+this.aid);
      localStorage.removeItem('meEndTime'+this.aid);
      localStorage.removeItem('canClick'+this.aid);
      document.getElementById("155").blur();
      let self = this
      let vis = '您是否确定提交？'
      for (let i = 0; i < this.modelForm.topic.length; i++) {
        if ( (this.modelForm.topic[i].type == '1' && this.modelForm.topic[i].answer == undefined)
            || (this.modelForm.topic[i].type == '3' && this.modelForm.topic[i].answer2 == undefined)
            || (this.modelForm.topic[i].type == '2' && this.modelForm.topic[i].checkList == undefined)) {
          vis = '您还有未作答的题目，确定提交吗'
          break
        }
      }
      ElMessageBox.confirm(
          vis,
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',

            type: 'warning',
          }
      ).then(() => {
        self.postRes()
        self.isSub = true
      })
    },
    getTo(item,index){

      console.log(this.modelForm.topic[index])
      let to
      let j
      let to1=[]
      let self = this
      item.answers.forEach(function (it){
        if(it.choiceText == item.answer){
          j=it.quesCount - 1
          to=it.toQuestion
          self.toQues[it.quesCount - 1].to=Math.max(to - 1,0)
        }else{
          to=it.toQuestion
          to1.push(Math.max(to - 1,0))
        }
      })
      self.toQues[j].notto=to1
      console.log(self.toQues)
      let s= new Map()
      for (let i = 0; i < this.modelForm2.topic.length; i++) {
        for (let k = 0; k < this.toQues[i].notto.length; k++) {
          let kk = this.toQues[i].notto[k]
          if(kk!=0){
            s.set(kk,1)
          }
        }
      }
      console.log(s)
      let forms=[]
      for (let i = 0; i < this.modelForm2.topic.length; i) {
        if(s.get(i) == 1){
          i++
          continue
        }
        console.log(this.modelForm2.topic[i].quesId)
        let vis = false
        this.modelForm.topic.forEach(function (it){
          console.log(it)
          if(it.quesId == self.modelForm2.topic[i].quesId){
            if(it.answer != undefined){
              forms.push(it)
              vis=true
            }
          }
        })
        if(!vis)
          forms.push(self.modelForm2.topic[i])

        if(self.toQues[i].to == 0) {
          i ++
          continue
        }
        i = self.toQues[i].to
        console.log(i)
      }
      console.log(this.modelForm2.topic.length)
      console.log(forms)
      this.modelForm.topic = forms
      console.log(this.modelForm.topic)


    },
    loadData() {
      let route = useRoute();
      let qid = route.query.qid;
      let aid = route.query.aid
      this.aid=aid
      this.qid=qid
      console.log(aid)
      var qNum = 0;
      var cNum = 0;
      let formData = new FormData();
      formData.append('qid',qid);
      let ans=[]
      let vis = false
      if(this.toQues.length > 1) vis = true
      this.$axios.post('http://localhost:8090/questionnaire/questionnaireInfo', formData).then(res=>res.data).then(
          res=>{
            this.times = res.data.questionnaire.answerTime
            console.log(res.data)
            for(;qNum<res.data.questions.length;qNum++){
              if(!vis) this.toQues.push({to:0,notto:[]})
              ans.push({ aid:aid,quesId:res.data.questions[qNum].questionId,type: res.data.questions[qNum].questionType, questionName: res.data.questions[qNum].questionText, answers: [], answer:'', answer2:[]});
              for(;cNum<res.data.choices.length;cNum++){
                if(res.data.choices[cNum].quesCount === res.data.questions[qNum].count){
                  ans[qNum].answers.push({ quesCount: res.data.choices[cNum].quesCount,toQuestion: res.data.choices[cNum].toQuestion,choiceText: res.data.choices[cNum].choiceText})
                }
              }
              cNum = 0;
            }
            if (this.modelForm.topic.length == 0){
              this.modelForm.topic=ans
              console.log(ans)
            }else{
              console.log(this.modelForm.topic)
            }

            this.modelForm2.topic = ans
          })
    }
  },
  beforeMount() {
    this.loadData()
  },
  created() {
    let route = useRoute();
    let aid = route.query.aid
    this.aid=aid
    console.log(this.aid)

    //localStorage.removeItem("form"+this.aid)
    if (JSON.parse(localStorage.getItem("form"+this.aid)) != null){
      let form = JSON.parse(localStorage.getItem("form"+this.aid))
      this.modelForm.topic = form
      console.log(form)
    }

    //localStorage.removeItem("toQues"+this.aid)
    if (JSON.parse(localStorage.getItem("toQues"+this.aid)) != null){
      let toQues = JSON.parse(localStorage.getItem("toQues"+this.aid))
      this.toQues = toQues
      console.log(toQues)
    }


    // localStorage.removeItem('myEndTime'+this.aid)
    // localStorage.removeItem('canClick'+this.aid)
    let myendTime = localStorage.getItem('myEndTime'+this.aid)
    let can = localStorage.getItem('canClick'+this.aid)
    this.canClick = can
    if (can) {
      this.getTime(myendTime)
    }

    window.addEventListener('beforeunload',()=>{
      console.log('页面刷新了')
      localStorage.setItem("form"+this.aid,JSON.stringify(this.modelForm.topic))
      localStorage.setItem("toQues"+this.aid,JSON.stringify(this.toQues))
    })
  }
}
</script>

<style scoped>
  .getRed{
    color: red;
  }
</style>
